package com.yao.club.service.impl;

import com.yao.club.entity.UserEntity;
import com.yao.club.entity.dto.SysImg;
import com.yao.club.entity.dto.UserProfile;
import com.yao.club.entity.request.ClubAuthRequestEntity;
import com.yao.club.entity.request.UpdateUserInfoRequest;
import com.yao.club.entity.result.LoginResultEntity;
import com.yao.club.entity.result.ResponseEntity;
import com.yao.club.entity.vo.UserProfileVO;
import com.yao.club.mapper.UserMapper;
import com.yao.club.reposittory.SysImageRepository;
import com.yao.club.reposittory.UserProfileRepository;
import com.yao.club.service.UserService;
import com.yao.club.token.TokenUtils;
import com.yao.club.utils.LogUtils;
import com.yao.club.utils.ResponseUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import shaded.org.apache.commons.lang3.RandomStringUtils;
import shaded.org.apache.commons.lang3.StringUtils;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private RedisTemplate<String, String> loginCodesRedisTemplate;
    @Autowired
    private RedisTemplate<String, String> forgetCodesRedisTemplate;

    @Autowired
    private UserProfileRepository userProfileRepository;
    @Autowired
    SysImageRepository sysImageRepository;

    @Resource
    UserMapper userMapper;
    /**
     * 发送登陆短信验证码
     * @param phoneNumber
     * @return
     */
    @Override
    public ResponseEntity<Boolean> sendLoginCode( String phoneNumber) {
        // 1. 生成6位随机数字验证码
        String code = RandomStringUtils.randomNumeric(6);
        // 2. 存入Redis（1分钟过期）
        String redisKey = "sms:login:" + phoneNumber;
        loginCodesRedisTemplate.opsForValue().set(redisKey, code, 1, TimeUnit.MINUTES);
        // 3. 调用短信服务发送（模拟）
        LogUtils.info("发送短信验证码到 {} : {}", phoneNumber, code);
        return ResponseUtils.success(true,code);
    }

    /**
     * 发送忘记密码短信验证码
     * @param phoneNumber
     * @return
     */
    @Override
    public ResponseEntity<Boolean> sendForgetPwdCode( String phoneNumber) {
        // 1. 生成6位随机数字验证码
        String code = RandomStringUtils.randomNumeric(6);
        // 2. 存入Redis（1分钟过期）
        String redisKey = "sms:forget:" + phoneNumber;
        forgetCodesRedisTemplate.opsForValue().set(redisKey, code, 1, TimeUnit.MINUTES);
        // 3. 调用短信服务发送（模拟）
        LogUtils.info("发送短信验证码到 {} : {}", phoneNumber, code);
        return ResponseUtils.success(true,code);
    }

    /**
     * 校验登陆验证码
     * @param entity
     * @return
     */
    @Override
    public ResponseEntity<LoginResultEntity> login(ClubAuthRequestEntity entity) {
        // 1. 从Redis获取验证码
        String redisKey = "sms:login:" + entity.userName;
        String correctCode = loginCodesRedisTemplate.opsForValue().get(redisKey);

        // 2. 校验验证码
        if (StringUtils.isEmpty(correctCode)) {
            return ResponseUtils.failed(400, "验证码已过期或未发送");
        }
        if (!correctCode.equals(entity.smsCode)) {
            return ResponseUtils.failed(400, "验证码已过期或未发送");
        }
        // 3. 验证通过后删除Redis中的验证码
        loginCodesRedisTemplate.delete(redisKey);
        // 4.判断是否注册过，若未注册注册
        UserEntity user = userMapper.select(entity.userName);
        if (user == null) {
            long maxSysUserId = userMapper.getMaxSysUserId()+1;
            int insert = userMapper.insert(maxSysUserId, entity.userName, "摩友" + maxSysUserId, entity.userName);
            if (insert < 0) {
                return ResponseUtils.failed("创建用户失败");
            }
        }
        // 5:生成token
        String token = TokenUtils.token(entity.userName);
        LoginResultEntity loginResultEntity = new LoginResultEntity();
        loginResultEntity.access_token = token;
        loginResultEntity.expires_in = "1758847094";
        return ResponseUtils.success(loginResultEntity);
    }
    /**
     * 账号密码登陆
     * @return
     */
    @Override
    public ResponseEntity<LoginResultEntity> loginByPwd(ClubAuthRequestEntity entity) {
        // 4.判断是否注册过，若未注册注册
        UserEntity user = userMapper.login(entity.userName,entity.password);
        if (user == null) {
           return ResponseUtils.failed(400, "账号或密码错误");
        }
        // 5:生成token
        String token = TokenUtils.token(entity.userName);
        LoginResultEntity loginResultEntity = new LoginResultEntity();
        loginResultEntity.access_token = token;
        loginResultEntity.expires_in = "1758847094";
        return ResponseUtils.success(loginResultEntity);
    }

    /**
     * 校验忘记密码验证码
     * @param entity
     * @return
     */
    @Override
    public ResponseEntity<Boolean> resetPwd(ClubAuthRequestEntity entity) {
        // 1. 从Redis获取验证码
        String redisKey = "sms:forget:" + entity.userName;
        String correctCode = forgetCodesRedisTemplate.opsForValue().get(redisKey);
        // 2. 校验验证码
        if (StringUtils.isEmpty(correctCode)) {
            return ResponseUtils.failed(400, "验证码已过期或未发送");
        }
        if (!correctCode.equals(entity.smsCode)) {
            return ResponseUtils.failed(400, "验证码已过期或未发送");
        }
        // 3. 验证通过后删除Redis中的验证码
        forgetCodesRedisTemplate.delete(redisKey);

        return ResponseUtils.success(true);
    }

    /**
     * 绑定新密码
     * @param entity
     * @return
     */
    @Override
    public ResponseEntity<Boolean> resetNewPwd(ClubAuthRequestEntity entity){
        if (!entity.password.equals(entity.newPassword)){
            return ResponseUtils.failed(400, "密码不一致");
        }

        int i = userMapper.setNewPwd(entity.password, entity.userName);
        if (i < 0) {
            return ResponseUtils.failed("修改密码失败");
        }
        return ResponseUtils.success(true);

    }

    /**
     * 一键登陆
     * @param phone 手机号
     * @return
     */
    @Override
    public ResponseEntity<LoginResultEntity> oneQuickLogin(String phone){
        // 判断是否注册过，若未注册注册
        UserEntity user = userMapper.select(phone);
        if (user == null) {
            long maxSysUserId = userMapper.getMaxSysUserId()+1;
            int insert = userMapper.insert(maxSysUserId, phone, "摩友" + maxSysUserId,phone);
            if (insert < 0) {
                return ResponseUtils.failed("创建用户失败");
            }
        }
        // 5:生成token
        String token = TokenUtils.token(phone);
        LoginResultEntity loginResultEntity = new LoginResultEntity();
        loginResultEntity.access_token = token;
        loginResultEntity.expires_in = "1758847094";
        return ResponseUtils.success(loginResultEntity);
    }

    @Override
    public ResponseEntity<UserProfileVO> getUserInfo(String  username) {
        UserEntity user = userMapper.select(username);
        if (user == null) {
            return ResponseUtils.failed("用户不存在");
        }

        UserProfile userProfile = userProfileRepository.findById(user.member_id).orElse(null);
        if (userProfile != null) {
            UserProfileVO userProfileVO = new UserProfileVO();
            // Map fields from UserProfile to UserProfileVO
            userProfileVO.setId(userProfile.getId());
            userProfileVO.setSyPayUserNo(userProfile.getSyPayUserNo());
            userProfileVO.setSyUserId(userProfile.getSyUserId());
            userProfileVO.setUsername(userProfile.getUsername());
            userProfileVO.setNickname(userProfile.getNickname());
            userProfileVO.setCellphone(userProfile.getCellphone());
            userProfileVO.setGender(userProfile.getGender());
            userProfileVO.setHobby(userProfile.getHobby());
            userProfileVO.setGiveLikes(userProfile.getGiveLikes());
            userProfileVO.setComments(userProfile.getComments());
            userProfileVO.setPosts(userProfile.getPosts());
            userProfileVO.setMessages(userProfile.getMessages());
            userProfileVO.setLikes(userProfile.getLikes());
            userProfileVO.setCollections(userProfile.getCollections());
            userProfileVO.setMedalImg(userProfile.getMedalImg());
            userProfileVO.setModelImg(userProfile.getModelImg());
            userProfileVO.setHasPassword(userProfile.getHasPassword());
            userProfileVO.setRealname(userProfile.getRealname());
            userProfileVO.setRelationStatus(userProfile.getRelationStatus());
            userProfileVO.setFansCount(userProfile.getFansCount());
            userProfileVO.setFollowCount(userProfile.getFollowCount());
            userProfileVO.setFriendsCount(userProfile.getFriendsCount());
            userProfileVO.setAccountStatus(userProfile.getAccountStatus());
            userProfileVO.setEquityName(userProfile.getEquityName());
            userProfileVO.setAvatarId(userProfile.getAvatarId());
            userProfileVO.setWeChat(userProfile.getWeChat());
            SysImg sysImg = sysImageRepository.selectById(String.valueOf(user.avatar_id));
            userProfileVO.setHeadImg(sysImg);
            return ResponseUtils.success(userProfileVO);
        }
        return ResponseUtils.failed("失败");
    }

    @Override
    public ResponseEntity<Boolean> updateUserInfo(String username, UpdateUserInfoRequest request) {
        try {
            UserProfile user = userProfileRepository.findUserProfileByUsername(username);
            if (user == null) {
                return ResponseUtils.failed("用户不存在");
            }

            // 更新用户信息
            user.setNickname(request.getNickName());
            user.setRealname(request.getRealName());
            user.setGender(request.getGender().equals("2") ? (byte) 1 : (byte) 2);
            user.setHobby(request.getHobby());
//            user.setAvatarId(request.getHeadImg() != null ?
//                    sysImageRepository.save(new SysImg(userProfileVO.getHeadImg())).getId() : user.getAvatarId());

            userProfileRepository.save(user);
            return ResponseUtils.success(true);
        } catch (Exception e) {
            return ResponseUtils.failed("修改用户信息失败：" + e.getMessage());
        }
    }
}
